<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 服务项目
 *
 * @icon fa fa-circle-o
 */
class Items extends Backend
{

    /**
     * Items模型对象
     * @var \app\admin\model\Items
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'name';
    protected $multiFields="status,home,recommend";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Items;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("itemTypeList", $this->model->getItemTypeList());
        $this->view->assign("agentList", $this->model->getAgentList());
        $this->view->assign("shopInList", $this->model->getShopInList());
        $this->view->assign("shopWayList", $this->model->getShopWayList());
    }
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(["gg","cate"])
                    ->where("item_type",1)
                    ->where($where)
                    ->count();
            $list = $this->model
                    ->with(["gg","cate"])
                    ->where("item_type",1)
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $this->modelValidate=true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['name']=trim($params['name']);
        $gg=$params['gg'];
        $gg=(array)json_decode($gg,true);
        if(!is_array($gg)){
            $this->error('服务规格不能为空');
        }
        if(count($gg)==0){
            $this->error('服务规格不能为空');
        }
        $imgs=\explode(",",$params['img_images']);
        $imgs=array_filter($imgs);
        if(count($imgs)>0){
            $params['face_image']=$imgs[0];
        }
        $params['body_con']=htmlspecialchars($params['body_con']);
        $params['price']=0;
        $params['dw']="";
        //检查$gg数组是否name值重复
        $gg_name=[];
        foreach($gg as $k=> &$v){
            $v['name']=trim($v['name']);
            $v['dw']=trim($v['dw']);
            if(in_array($v['name'],$gg_name)){
                $this->error('服务规格名称【'.$v['name'].'】不能重复');
            }
            $gg_name[]=$v['name'];
            $v['price']=floatval($v['price']);
            $v['dw']=$v['dw']==''?'次':$v['dw'];
            if($v['price']<0){
                $this->error('服务规格【'.$v['name'].'】价格不能为负数');
            }
            if($k==0){
                $params['price']=$v['price'];
                $params['dw']=$v['dw'];
            }
            if($params['price']>$v['price']){
                $params['price']=$v['price'];
                $params['dw']=$v['dw'];
            }
        }
        if($params['worker_fc_bl']<0 || $params['worker_fc_bl']>100){
            $this->error('分成只能是0-100之间的数字');
        }
        //分销分佣检查
        $params['anget_lev1']=floatval($params['anget_lev1']);
        $params['anget_lev2']=floatval($params['anget_lev2']);
        if($params['anget']==1){
            if($params['anget_lev1']<=0 || $params['anget_lev1']>100){
                $this->error('上级返佣只能是0-100之间的数字，且不能为0');
            }
            if($params['anget_lev2']<0 || $params['anget_lev2']>100){
                $this->error('上上级返佣只能是0-100之间的数字');
            }
            //合并服务分成检查是否超出100%
            $total_bl=bcadd($params['worker_fc_bl'],$params['anget_lev1'],2);
            $total_bl=bcadd($total_bl,$params['anget_lev2'],2);
            if($total_bl>100){
                $this->error('服务分成加上分销分佣不能超过100%，请检查！');
            }
        }else{
            $params['anget_lev1']=0;
            $params['anget_lev2']=0;
        }
        Db::startTrans();
        try {
            $this->model->validateFailException()->validate(
                ['name' => ['unique'=>"deerhome_items,name"]],
			    ['name.unique'=> '服务名称已经存在，请更换']
            );
            $result = $this->model->allowField(true)->save($params);
            $this->model->gg()->saveAll($gg);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error('err:'.$e->getMessage());
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['body_con']=htmlspecialchars_decode($row['body_con']);
            $items_gg = $this->model->gg()->where('jz_items_id',$row['id'])->field("name,price,dw")->select();
            $items_gg=collection($items_gg)->toArray();
            $items_gg=json_encode($items_gg,JSON_UNESCAPED_UNICODE);
            $shop_list=$row['shop_list']?$row['shop_list']:'[]';
            $this->view->assign('items_gg', $items_gg);
            $this->view->assign('shop_list', $shop_list);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['name']=trim($params['name']);
        $params['body_con']=htmlspecialchars($params['body_con']);
        $params = $this->preExcludeFields($params);
        
        $gg=$params['gg'];
        $gg=(array)json_decode($gg,true);
        if(!is_array($gg)){
            $this->error('服务规格不能为空');
        }
        if(count($gg)==0){
            $this->error('服务规格不能为空');
        }
        $params['price']=0;
        $params['dw']="";
        $imgs=\explode(",",$params['img_images']);
        $imgs=array_filter($imgs);
        if(count($imgs)>0){
            $params['face_image']=$imgs[0];
        }
        //检查$gg数组是否name值重复
        $gg_name=[];
        foreach($gg as $k=>&$v){
            $v['jz_items_id']=$row['id'];
            $v['name']=trim($v['name']);
            $v['dw']=trim($v['dw']);
            if(in_array($v['name'],$gg_name)){
                $this->error('服务规格名称【'.$v['name'].'】不能重复');
            }
            $gg_name[]=$v['name'];
            $v['price']=floatval($v['price']);
            $v['dw']=$v['dw']==''?'次':$v['dw'];
            if($v['price']<0){
                $this->error('服务规格【'.$v['name'].'】价格不能为负数');
            }
            $v['hash']=md5($v['jz_items_id'].$v['name']);
            if($k==0){
                $params['price']=$v['price'];
                $params['dw']=$v['dw'];
            }
            if($params['price']>$v['price']){
                $params['price']=$v['price'];
                $params['dw']=$v['dw'];
            }
        }
        if($params['worker_fc_bl']<0 || $params['worker_fc_bl']>100){
            $this->error('分成只能是0-100之间的数字');
        }
        //分销分佣检查
        $params['anget_lev1']=floatval($params['anget_lev1']);
        $params['anget_lev2']=floatval($params['anget_lev2']);
        if($params['anget']==1){
            if($params['anget_lev1']<=0 || $params['anget_lev1']>100){
                $this->error('上级返佣只能是0-100之间的数字，且不能为0');
            }
            if($params['anget_lev2']<0 || $params['anget_lev2']>100){
                $this->error('上上级返佣只能是0-100之间的数字');
            }
            //合并服务分成检查是否超出100%
            $total_bl=bcadd($params['worker_fc_bl'],$params['anget_lev1'],2);
            $total_bl=bcadd($total_bl,$params['anget_lev2'],2);
            if($total_bl>100){
                $this->error('服务分成加上分销分佣不能超过100%，请检查！');
            }
        }else{
            $params['anget_lev1']=0;
            $params['anget_lev2']=0;
        }
        $result = false;
        Db::startTrans();
        try {
            $row->validateFailException()->validate(
                ['name' => ['unique'=>"deerhome_items,name,{$row['id']}"]],
			    ['name.unique'=> '服务名称已经存在，请更换']
            );
            $result = $row->allowField(true)->save($params);
            $this->model->gg()->where('jz_items_id',$row['id'])->delete();
            (new \app\admin\model\deerhome\ItemsGg)->saveAll($gg);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
       
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::name("deerhome_items_gg")->where('jz_items_id','in',$ids)->delete();
            //清理用户收藏、足迹
            Db::name("deerhome_user_collected")->where('jz_items_id','in',$ids)->delete();
            Db::commit();
        } catch (PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
